// 认证控制器

import userService from '../services/userService.js'
import userValidator from '../validators/userValidator.js'
import { successResponse, errorResponse, createdResponse } from '../utils/response.js'

/**
 * 用户注册
 */
const register = async (req, res) => {
  try {
    const { isValid, errors } = userValidator.validateRegisterData(req.body)
    
    if (!isValid) {
      return errorResponse(res, errors.join(', '))
    }
    
    const user = await userService.createUser(req.body)
    const token = userService.generateToken(user)
    
    return createdResponse(res, { token, user: { id: user.id, username: user.username } }, '注册成功')
  } catch (error) {
    return errorResponse(res, error.message)
  }
}

/**
 * 用户登录
 */
const login = async (req, res) => {
  try {
    const { isValid, errors } = userValidator.validateLoginData(req.body)
    
    if (!isValid) {
      return errorResponse(res, errors.join(', '))
    }
    
    const user = await userService.authenticateUser(req.body.username, req.body.password)
    const token = userService.generateToken(user)
    
    return successResponse(res, { token, user: { id: user.id, username: user.username } }, '登录成功')
  } catch (error) {
    return errorResponse(res, error.message)
  }
}

export default {
  register,
  login
} 